<template>
    <div class="json-root">
        <json-node :conf="conf" :jsonData="jsonData" @selectNode="selectNode" :selectNodeFunc="selectNode"></json-node>

        <div class="detail-button">
            <el-button type="primary" @click="expand">展开</el-button>
            <el-button class="copy_btn" type="primary" @click=copy>复制</el-button>
            <el-button class="copy_btn" type="primary" @click=initExcel>初始化Excel</el-button>
        </div>
        <div class="json-value" v-if="expandFlag">
            <span v-text="tips"></span>
            <div class="copy" v-html="value"></div>
        </div>
    </div>
</template>
<script>
import { createJsonConf, getJsonKeys } from "src/utils/key_parser";
import Clipboard from "clipboard";
import { officeUtils } from 'src/utils/office/office_util';
export default {
  data() {
    let jsonData = {
      user: {
        id: 1,
        name: "名字",
        company: {
          id: 12,
          name: "wl-pro-lims",
          addr: "GZ",
          list: ["a", "b", "c"]
        }
      },
      list: [
        {
          id: 100,
          flag: true
        },
        {
          id: 102,
          sex: 1
        }
      ],
      numList: [101, 122, 112233, "abcd"]
    };

    let conf = createJsonConf(jsonData, "", 0);
    try{
        let list = getJsonKeys(jsonData);
        this.$message.success(list.join('; '))
    }catch(e){
        this.$message.warning(e + '')
    }
    // console.log(list);
    return {
      jsonData,
      conf,
      tips: "",
      value: "",
      rawJson: "",
      expandFlag: false
    };
  },

  methods: {
    selectNode(param) {
      let val = JSON.stringify(param.val, null, 4);
      this.rawJson = val;
      val = val.replace(/\r\n/g, "\n");
      val = val.replace(/\r/g, "\n");
      val = val.replace(/\n/g, "<br>");
      val = val.replace(/\s/g, "&nbsp;");
      this.value = val;
      console.log("select node", param, /\n/.test(this.value));
    },
    copy() {
      console.log("start copy");
      if (this.rawJson != "") {
        let self = this;
        var clipboard = new Clipboard(".copy_btn", {
          text: function() {
            return self.rawJson;
          }
        });
        clipboard.on("success", e => {
          // this.tips = '复制成功'
          self.$message.success("复制成功");
          console.log("复制成功");
          // 释放内存
          clipboard.destroy();
        });
        clipboard.on("error", e => {
          // 不支持复制
          console.log("该浏览器不支持自动复制");
          // 释放内存
          clipboard.destroy();
        });
      }else{
          this.$message.warning('先选择 json 节点')
      }
    },
    expand() {
      this.expandFlag = !this.expandFlag;
    },
    initExcel(){
        officeUtils.addConfig((param)=>{
            this.$message.success('config already exist' + param)
        }, this);
    }
  },

  mounted() {}
};
</script>
